var common = require('../../common');
var pool = require('../index');
var mysql = require('mysql');
var YjxBaseModel = require('./YjxBaseModel');
var CONFIG = require('../../config');


var YjxActFinanceHis = function (obj) {
    YjxBaseModel.call(this,obj);

    //`his_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '纪录id',
    //`user_id` bigint(20) NOT NULL DEFAULT '0' COMMENT '用户id',
    //`aur_id` bigint(20) DEFAULT NULL COMMENT '用户奖励纪录id',
    //`cash_platform` int(2) NOT NULL DEFAULT '10' COMMENT '提现平台: 10微信, 20支付宝',
    //`cash_account` varchar(100) NOT NULL DEFAULT '' COMMENT '提现帐号: 根据提现平台确定',
    //`cash_state` int(2) NOT NULL DEFAULT '10' COMMENT '提现状态: 10新建, 20打款成功',
    //`cash_amt` bigint(20) NOT NULL DEFAULT '0' COMMENT '提现金额(分)',
    //`taxes` bigint(20) NOT NULL DEFAULT '0' COMMENT '税额(分)',
    //`state` int(3) unsigned NOT NULL DEFAULT '10' COMMENT '状态:10有效，20冻结，30无效 （待定字段）',
    //`desc` varchar(200) DEFAULT '' COMMENT '备注',
    //`create_time` datetime NOT NULL,
    //`update_time` datetime NOT NULL,
    //`update_by` varchar(50) DEFAULT NULL,
    //`del_flg` int(1) NOT NULL DEFAULT '0',

};

YjxActFinanceHis.prototype = new YjxBaseModel();

// 取得表名
YjxActFinanceHis.prototype.getTableName = function(){
    return 'yjx_act_finance_his';
};
// 取得查询语句中where 后面匹配主键的条件（需要各派生类进行重载）
YjxActFinanceHis.prototype.getWhereConditionOfKeyEqual = function(){
    return 'his_id='+this.his_id;
};

/**
 * 用户申请提现_ APP_1_7 添加
 *
 *
 * @author jackLiu
 * @date   2018-6-8
 *
 * device   6 字段为 一键秀 相关标记
 * userId   用户唯一标识
 * cashAmount   提现金额, 单位: 分，例如：19998
 * account  提现账户，例如：18888888888@taobao.com
 * accountPlatform  提现平台, 10 微信, 20 支付宝
 * cash_threshold   提现门槛,余额大于此数才能提现 单位: 分 ，例如：19998
 * @param callback  回调
 *          errCode: 错误码：0表示成功，11表示参数错误，12表示余额为0， 13表示金额没达到提现门槛，21属于合作公司的个人用户不能直接提现，31表示处理失败
 *
 */
YjxActFinanceHis.prototype.applyCashReward_v1_7 = function (device,userId,cashAmount,account,accountPlatform,cashThreshold,callback){

    pool.pool.getConnection(function(err, connection) {
        if(err) {
            console.log("YjxActFinanceHis.js [applyCashReward_v1_7] getConnection err: "+ err);
            return callback(err, null);
        }
        var sql = "call proc_yjx_apply_cash_reward(" + device +" ," + userId +" , " + cashAmount + " , '" + account + "' , " + accountPlatform +","+cashThreshold + ", @f_result" + ")";
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            //console.log();
            if(error) {
                console.log(error);
                return callback(31);
            }
            if(!result || result.length==0 || result[0].length==0 || !(result[0][0].hasOwnProperty("f_result"))){
                return callback(31);
            }
            // 0表示成功，11表示参数错误，12表示余额为0， 13表示金额没达到提现门槛，14表示处理失败，21属于合作公司的个人用户不能直接提现
            var f_result = result[0][0].f_result;
            return callback(f_result);
        });
    });
};
/**
 * 获取用户已提现总金额
 *
 * @author 李强
 * @date 2018-06-09
 *@param userId         用户唯一标识
 * @param callback
 */
YjxActFinanceHis.prototype.getUserAlreadyCash = function(userId,callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('YjxActFinanceHis.getUserAlreadyCash Err:'+err);
        }

        var sql = 'SELECT SUM(yafh.cash_amt) AS alreadyCash ' +
            ' from yjx.yjx_act_finance_his yafh ' +
            ' WHERE yafh.user_id = ' + userId +
            ' AND yafh.del_flg = 0 ' +
            ' AND yafh.cash_state=20';

        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            callback(error, result);
        });
    });
};



/**
 * 获取用户提现处理中总金额
 *
 * @author 李强
 * @date 2018-06-09
 *@param userId         用户唯一标识
 * @param callback
 */
YjxActFinanceHis.prototype.getUserProcessCash = function(userId,callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('YjxActFinanceHis.getUserProcessCash Err:'+err);
        }

        var sql = 'SELECT SUM(yafh.cash_amt) AS processCash ' +
            ' from yjx.yjx_act_finance_his yafh ' +
            ' WHERE yafh.user_id = ' + userId +
            ' AND yafh.del_flg = 0 ' +
            ' AND yafh.cash_state IN (10,30,40)';

        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            callback(error, result);
        });
    });
};

/**
 * 获取用户当天提现信息
 *
 * @author 王俊
 * @date 2018-06-09
 *
 * @param userId    用户唯一标识
 * @param callback  回调函数
 *          err:    查询失败
 *          data: {
 *              currentDayCashTimes: 当天提现次数
 *              currentDayCashAmount: 当天提现金额
 *          }
 */
YjxActFinanceHis.prototype.getUserCurrentDayCashInfo = function (userId, callback) {
    pool.pool.getConnection(function(getConErr, connection) {
        if (getConErr) {
            console.log('YjxActFinanceHis.getUserCurrentDayCashInfo getConErr:'+getConErr);
        }
        var sql =
            ' SELECT count(0) AS currentDayCashTimes, ' +
            '        sum(yafh.cash_amt) AS currentDayCashAmount, ' +
            '        yafh.* ' +
            ' FROM yjx.yjx_act_finance_his yafh ' +
            ' WHERE yafh.del_flg = 0 ' +
            '   AND yafh.user_id = ' + userId +
            '   AND yafh.state = 10 ' +
            '   AND date(yafh.create_time) = curdate()';
        console.log(sql);
        connection.query(sql, function(queryErr, results) {
            // And done with the connection.
            connection.release();
            if(queryErr) {
                return callback(queryErr)
            }
            if(!results || results.length <=0) {
                return callback(null, null);
            }
            return callback(queryErr, results[0]);
        });
    });
};

/**
 * 获取用户最后一次提现账户
 *
 * @author 王俊
 * @date 2018-06-09
 *
 * @param userId    用户唯一标识
 * @param callback  回调函数
 *          err:    查询失败
 *          data: {
 *              lastCashPlatform: 最近一次的提现平台
 *              lastCashAccount: 最近一次的提现账户
 *          }
 */
YjxActFinanceHis.prototype.getUserLastCashAccount = function (userId,device, callback) {
    pool.pool.getConnection(function(getConErr, connection) {
        if (getConErr) {
            console.log('YjxActFinanceHis.getUserLastCashAccount getConErr:'+getConErr);
        }
        var sql =
            ' SELECT yafh.cash_platform AS lastCashPlatform, ' +
            '        yafh.cash_account AS lastCashAccount ' +
            ' FROM yjx.yjx_act_finance_his yafh ' +
            ' WHERE yafh.del_flg = 0 ' +
            '   AND yafh.user_id = ' + userId +
            '   AND yafh.device = ' + device +
            ' ORDER BY yafh.create_time DESC LIMIT 1 ';
        console.log(sql);
        connection.query(sql, function(queryErr, results) {
            // And done with the connection.
            connection.release();
            if(queryErr) {
                return callback(queryErr)
            }
            if(!results || results.length <=0) {
                return callback(null, null);
            }
            return callback(queryErr, results[0]);
        });
    });
};


/**
 * (网红)公司计算某个活动的收益
 *
 * @author jackLiu
 * @date 2018-6-12
 *
 * @param   orgId  组织id
 * @param   activityId  活动id
 * @param   callback
 *              error: 错误
 *              data: 收益，单位：分
 */
YjxActFinanceHis.prototype.calcPatnerActivityReward = function (orgId,activityId,callback){

    pool.pool.getConnection(function(err, connection) {
        if(err) {
            console.log("YjxActFinanceHis.js [calcPatnerActivityReward] getConnection err: "+ err);
            return callback(err, null);
        }
        var sql = "call proc_yjx_calc_partner_activity_reward(" + orgId +" , " + activityId +  ", 0, @f_result" + ")";
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            //console.log();
            if(error) {
                console.log(error);
                return callback(error,0);
            }
            if(!result || result.length==0 || result[0].length==0 || !(result[0][0].hasOwnProperty("f_result"))){
                return callback("错误",0);
            }
            // 返回可提现总金额
            var f_result = result[0][0].f_result;
            return callback(null, f_result);
        });
    });
};

/**
 * (网红)公司对某个活动的收益进行记账
 *
 * @author jackLiu
 * @date 2018-6-12
 *
 * @param   orgId  组织id
 * @param   activityId  活动id
 * @param   reward  活动中该组织的总收益额，单位：分
 * @param   tax  所缴纳的税款，单位：分[目前传0即可]
 * @param   callback
 *              errCode: 错误码， 0表示成功，11表示参数错误，12表示余额为0，13表示输入的总收益与实际总收益不相同， 14表示处理失败
 */
YjxActFinanceHis.prototype.recordPartnerActivityCash = function (orgId,activityId,reward,tax,callback){

    pool.pool.getConnection(function(err, connection) {
        if(err) {
            console.log("YjxActFinanceHis.js [recordPartnerActivityCash] getConnection err: "+ err);
            return callback(err, null);
        }
        var sql = "call proc_yjx_record_partner_activity_cash(" + orgId +" , " + activityId+" , " + reward+" , " + tax +  ", @f_result" + ")";
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            //console.log();
            if(error) {
                console.log(error);
                return callback(14);
            }
            if(!result || result.length==0 || result[0].length==0 || !(result[0][0].hasOwnProperty("f_result"))){
                return callback(14);
            }
            // 返回可提现总金额
            var f_result = result[0][0].f_result;
            return callback(f_result);
        });
    });
};



module.exports = YjxActFinanceHis;

